<template>
  <div>
    <div class="flex-between mb-16">
      <h2>产品管理</h2>
      <a-button type="primary" @click="handleAdd">
        <PlusOutlined />
        新建产品
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'cover_image'">
          <a-image v-if="record.cover_image" :width="80" :src="record.cover_image" />
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'default'">
            {{ record.status === 1 ? '已发布' : '草稿' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定删除这个产品吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新建/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="800px"
    >
      <a-form :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="产品名称" required>
          <a-input v-model:value="formState.name" placeholder="请输入产品名称" />
        </a-form-item>
        <a-form-item label="副标题">
          <a-input v-model:value="formState.subtitle" placeholder="请输入副标题" />
        </a-form-item>
        <a-form-item label="封面图">
          <ImageUpload v-model="formState.cover_image" placeholder="请输入封面图URL或点击上传" />
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea v-model:value="formState.summary" :rows="3" placeholder="请输入简介" />
        </a-form-item>
        <a-form-item label="排序">
          <a-input-number v-model:value="formState.sort_order" :min="0" style="width: 100%" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">发布</a-radio>
            <a-radio :value="0">草稿</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getProducts, createProduct, updateProduct, deleteProduct } from '@/api/product'
import ImageUpload from '@/components/ImageUpload/index.vue'
import type { Product } from '@/types'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '产品名称', dataIndex: 'name', key: 'name' },
  { title: '封面图', dataIndex: 'cover_image', key: 'cover_image', width: 100 },
  { title: '浏览量', dataIndex: 'view_count', key: 'view_count', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
  { title: '操作', key: 'action', width: 150 }
]

const dataSource = ref<Product[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const modalVisible = ref(false)
const modalTitle = ref('新建产品')
const editId = ref<number>()
const formState = reactive<Partial<Product>>({
  name: '',
  subtitle: '',
  cover_image: '',
  summary: '',
  sort_order: 0,
  status: 1
})

const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await getProducts({
      page: pagination.current,
      page_size: pagination.pageSize
    })
    dataSource.value = res.data.items
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取产品列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchProducts()
}

const handleAdd = () => {
  modalTitle.value = '新建产品'
  editId.value = undefined
  Object.assign(formState, {
    name: '',
    subtitle: '',
    cover_image: '',
    summary: '',
    sort_order: 0,
    status: 1
  })
  modalVisible.value = true
}

const handleEdit = (record: Product) => {
  modalTitle.value = '编辑产品'
  editId.value = record.id
  Object.assign(formState, {
    name: record.name,
    subtitle: record.subtitle,
    cover_image: record.cover_image,
    summary: record.summary,
    sort_order: record.sort_order,
    status: record.status
  })
  modalVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (editId.value) {
      await updateProduct(editId.value, formState)
      message.success('更新成功')
    } else {
      await createProduct(formState)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchProducts()
  } catch (error) {
    console.error('提交失败', error)
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleDelete = async (id: number) => {
  try {
    await deleteProduct(id)
    message.success('删除成功')
    fetchProducts()
  } catch (error) {
    console.error('删除失败', error)
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

